package cloud.xiguapi.ubas.service.impl;

import cloud.xiguapi.ubas.analysis.hotitems.KafkaHotItemsAnalysis;
import cloud.xiguapi.ubas.common.ApiResult;
import cloud.xiguapi.ubas.common.Pager;
import cloud.xiguapi.ubas.entity.KafkaHotItems;
import cloud.xiguapi.ubas.exceptions.ApiException;
import cloud.xiguapi.ubas.mapper.KafkaHotItemsMapper;
import cloud.xiguapi.ubas.service.IKafkaHotItemsService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author 大大大西西瓜皮🍉
 * date: 2021-5-24 下午 04:18
 * desc:
 */
@Service
@Slf4j
@Transactional(readOnly = true, rollbackFor = ApiException.class)
public class KafkaHotItemsServiceImpl implements IKafkaHotItemsService<KafkaHotItems> {

    private final KafkaHotItemsMapper kafkaHotItemsMapper;

    private final KafkaHotItemsAnalysis kafkaHotItemsAnalysis;

    @Autowired
    public KafkaHotItemsServiceImpl(KafkaHotItemsMapper kafkaHotItemsMapper, KafkaHotItemsAnalysis kafkaHotItemsAnalysis) {
        this.kafkaHotItemsMapper = kafkaHotItemsMapper;
        this.kafkaHotItemsAnalysis = kafkaHotItemsAnalysis;
    }

    @Override
    public ApiResult<Object> analysis() {
        try {
            log.info("Kafka实时热门商品统计分析任务");
            kafkaHotItemsAnalysis.analysis();
            return ApiResult.success(Optional.empty(), "Kafka实时热门商品统计分析任务完成。");
        } catch (Exception e) {
            log.error("Kafka实时热门商品分析失败, 原因:\n {}", e.getMessage());
            return ApiResult.failed("Kafka实时热门商品统计分析任务失败。");
        }
    }

    @Override
    public ApiResult<Pager<KafkaHotItems>> selectPage(long current, long size) {
        log.info("查询Kafka实时热门商品统计数据, 参数: current = {}, size = {}", current, size);

        IPage<KafkaHotItems> page = kafkaHotItemsMapper.selectPage(new Page<>(current, size));
        return ApiResult.success(Pager.<KafkaHotItems>builder()
                .current(page.getCurrent())
                .size(page.getSize())
                .total(page.getTotal())
                .records(page.getRecords())
                .build());
    }
}
